<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>节流throttle</title>
</head>
<body>
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
  <li>7</li>
  <li>8</li>
  <li>9</li>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
  <li>7</li>
  <li>8</li>
  <li>9</li>
</ul>
</body>
<style>
  body{
    display: flex;
    justify-content: center;
  }
  ul, li {
    padding:0;
    margin: 0;
  }
  li{
    width: 250px;
    height:200px;
    list-style: none;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  li:nth-child(2n){
    background:whitesmoke;
  }
  li:nth-child(2n+1){
    background:yellow;
  }
</style>
<script>
  // 首尾节流，计时器+时间戳
  function throttle(fn, delay){
    let timer = null
    let startTime = 0
    return function(...args){
      let curTime = Date.now();
      // 判断时间
      let remaining = delay - (curTime - startTime)
      // 清除旧的计时器
      clearTimeout(timer)
      // 如果时间间隔超过了delay 可以直接执行了  这是首节流（首次触发立即执行，停止触发后，没办法再次执行）
      if(remaining <= 0 ){
        fn.apply(this, args)
        startTime = Date.now()
      }else{
        // 否则如果还在delay时间内 等一会再执行 保证一段delay之内，只调用一次函数.这是尾节流（不会立即执行，而是在delay之后执行且在最后停止触发之后，还会执行一次）
        timer = setTimeout(()=>{
          fn.apply(this, args)
          startTime = Date.now()
        }, remaining)
      }
    }
  }


  function handle(){
    console.log(new Date())
  }

  const throttleHandler = throttle(handle, 500)
  console.log('tt', throttleHandler)
  window.addEventListener('scroll', throttleHandler)
</script>
</html>
